<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>用户注册</title>
	<style type="text/css">
		#panel {
			/* height: 100px; */
			/*高度*/
			width: 350px;
			/*宽度*/
			margin: 200px auto;
			/*面板距离浏览器顶部200px,居中*/
			padding: 20px;
			/*面板中内容距离面板边框20px*/
			background: #ccc;
			/*面板颜色为灰色*/
		}

		span {
			color: #F00;
		}
	</style>

</head>

<body>
	<?php
	include "conn.php";
	function filterInput($data)
	{
		$data = trim($data); //不必要的字符 (如：空格，tab，换行)。

		$data = stripslashes($data); //去除反斜杠 (\)

		$data = htmlspecialchars($data); //去除反斜杠 (\)

		return $data;
	}
	$nameErr = "";
	$passErr = "";
	if ($_SERVER["REQUEST_METHOD"] == "POST") {
		$user_name = $_POST["user_name"];
		$user_pass = $_POST["user_pass"];
		$user_name = filterInput($user_name);
		$user_pass = filterInput($user_pass);
		if (empty($user_name)) {
			$nameErr = "用户名为空";
		}
		if (empty($user_pass)) {
			$passErr = "密码为空";
		}

		if ($nameErr == '' and $passErr == '') {
			//连接数据库
			//$conn=mysqli_connect("localhost","root","","student","3308") or die("数据库连接失败");

			$sql = "select * from user where user_name=$user_name ";

			$result = mysqli_query($conn, $sql) or die("查询失败，请检查SQL语法");
			if (mysqli_num_rows($result) > 0) {
				echo "<script language='javascript' type='text/javascript'>";
				echo "alert('用户已经注册，请设置其他用户名');";
				echo "</script>";
			} else {
				$pass_hash = password_hash($user_pass, PASSWORD_DEFAULT);
				$sql = "insert into user(user_name,user_pass) values('$user_name','$pass_hash')";

				$result = mysqli_query($conn, $sql) or die("插入失败，请检查SQL语法");

				echo "<script language='javascript' type='text/javascript'>";
				echo "alert('用户注册成功');";
				echo "location.href='login.php';";
				echo "</script>";
			}
		}
	}
	?>
	<div id="panel">
		<form name="reg" method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
			<table>
				<tr>
				<h2 align="center" style="color:#66f">账号注册</h2>
					<td>请输入用户名：</td>
					<td><input type="text" name="user_name" /><span>*<?php echo $nameErr; ?></span></td>
				</tr>
				<tr>
					<td>请输入密码：</td>
					<td><input type="password" name="user_pass" /><span>*<?php echo $passErr; ?></span></td>
				</tr>
				<tr>
					<td colspan=""><input type="submit" value="注册" /></td>
					<td colspan="">

						<a href="./login.php" target="_top"> <button type="button">登陆</button></a>

					</td>
				</tr>

		</form>

	</div>

</body>

</html>